<?php

namespace app\api\service;

use app\model\Money;
use app\model\WatchAdRecord;
use think\facade\Cache;
use app\model\UserLove;
use app\common\Common;
use app\common\Error;
use app\model\VideoDetails;
use app\model\Videos;
use think\facade\Db;
use app\model\User;
use app\model\WatchPayRecord;
use app\model\Records;
use app\model\BingeWatch;
use app\model\Search;
use app\model\VideoPayConfig;
use think\facade\Log;
use app\model\PayRecord;
use app\model\Link;
use app\model\Applet;
use app\model\MountedAppletCustomRechargeConfig;
use app\model\CustomRechargeTemplate;
use app\model\ResponsibilityPerson;
use app\model\Company;
use app\model\VideoTemplate;
class VideoService
{
    private $userLoveModel;
    private $videoDetailsModel;
    private $videosModel;
    private $userModel;
    private $watchPayRecordModel;
    private $recordsModel;
    private $bingeWatchModel;
    private $searchModel;
    private $videoPayConfigModel;
    private $payRecordModel;
    private $linkModel;
    private $appletModel;
    private $mountedAppletCustomRechargeConfigModel;
    private $customRechargeTemplateModel;
    private $responsibilityPersonModel;
    private $companyModel;
  /**
     * @var Redis
     */
    private $redis;
    private $videoTemplateModel;

    public function __construct(
        UserLove $userLoveModel,
        VideoDetails $videoDetailsModel,
        Videos $videosModel,
        User $userModel,
        WatchPayRecord $watchPayRecordModel,
        Records $recordsModel,
        BingeWatch $bingeWatchModel,
        Search $searchModel,
        VideoPayConfig $videoPayConfigModel,
        PayRecord $payRecordModel,
        Link $linkModel,
        Applet $appletModel,
        MountedAppletCustomRechargeConfig $mountedAppletCustomRechargeConfigModel,
        CustomRechargeTemplate $customRechargeTemplateModel,
        VideoTemplate $videoTemplateModel,
	ResponsibilityPerson $responsibilityPersonModel,
        Company $companyModel
    )
    {
        $this->userLoveModel = $userLoveModel;
        $this->videoDetailsModel = $videoDetailsModel;
        $this->videosModel = $videosModel;
        $this->userModel = $userModel;
        $this->watchPayRecordModel = $watchPayRecordModel;
        $this->recordsModel = $recordsModel;
        $this->bingeWatchModel = $bingeWatchModel;
        $this->searchModel = $searchModel;
        $this->videoPayConfigModel = $videoPayConfigModel;
        $this->payRecordModel = $payRecordModel;
        $this->linkModel = $linkModel;
        $this->appletModel = $appletModel;
        $this->mountedAppletCustomRechargeConfigModel = $mountedAppletCustomRechargeConfigModel;
        $this->customRechargeTemplateModel = $customRechargeTemplateModel;
        $this->videoTemplateModel = $videoTemplateModel;
	    $this->redis = Cache::store('redis')->handler();
        $this->responsibilityPersonModel=$responsibilityPersonModel;
        $this->companyModel=$companyModel;
    }

    /**
     * 点赞和取消点赞
     * 
     * @dateTime 2022/09/03
     * @author zhixiang0215@126.com
     * @param int video_detail_id
     * @param int uid
     * @return bool
     */
    public function thumbUpOperation($videoDetailId, $uid)
    {
        $data = $this->videoDetailsModel->getInfoById($videoDetailId, 'id, video_id');
        $isLove = $this->userLoveModel->getInfoByWhere(['uid' => $uid, 'video_detail_id' => $videoDetailId, 'video_id' => $data['video_id']]);

        Db::startTrans();
        try {
            //改redis计数
            $redisCacheSwitch = config('trace.redis_cache_switch');
            if ($redisCacheSwitch) {
                $redis = Cache::store('redis')->handler();
                $redis->select(2);
                $videoKey = config('redis_key.video_statistic_count_key');
                $videoDetailKey = config('redis_key.video_detail_statistic_count_key').$data['video_id'];
            }
            if ($isLove) {
                // 取消点赞
                $delBool = Db::name('user_love')->where(['id' => $isLove['id']])->delete();
                //$decVideoDetailsBool = Db::name('video_details')->where(['id' => $videoDetailId])->dec('give_count', 1)->update();
                //$decVideoBool = Db::name('videos')->where(['id' => $data['video_id']])->dec('give_count', 1)->update();

                if (!$delBool) {
                    Db::rollback();
                    return false;
                }
                if ($redisCacheSwitch) {
                    $video_give_count = $redis->hGet($videoKey, 'give_count_'.$data['video_id']) ?: 0;
                    $detail_give_count = $redis->hGet($videoDetailKey, 'give_count_'.$videoDetailId) ?: 0;

                    $redis->hSet($videoKey, 'give_count_'.$data['video_id'], $video_give_count-1);
                    $redis->hSet($videoDetailKey,'give_count_'.$videoDetailId, $detail_give_count-1);
                }
            } else {
                // 点赞
                $insertBool = Db::name('user_love')->insert([
                    'uid'             => $uid,
                    'video_detail_id' => $videoDetailId,
                    'video_id'        => $data['video_id'],
                    'created_at'     => time(),
                    'updated_at'     => time()
                ]);

                //$incVideoDetailsBool = Db::name('video_details')->where(['id' => $videoDetailId])->inc('give_count', 1)->update();
                //$incVideoBool = Db::name('videos')->where(['id' => $data['video_id']])->inc('give_count', 1)->update();

                if (!$insertBool) {
                    Db::rollback();
                    return false;
                }
                if ($redisCacheSwitch) {
                    $redis->hIncrBy($videoKey, 'give_count_'.$data['video_id'], 1);
                    $redis->hIncrBy($videoDetailKey, 'give_count_'.$videoDetailId, 1);
                }
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Log::record('点赞和取消点赞异常：'.$e->getMessage());
            Db::rollback();
            return false;
        }
    }

    /**
     * 获取推荐视频数据
     * 
     * @dateTime 2022/09/03
     * @author zhixiang0215@126.com
     * @param array params
     * @param int uid
     * @return array
     */
    public function getRecommendVideoData(array $params, int $uid)
    {
        $playPlatform = $params['play_platform'] ?? 1; // by add huangxiaoshan 2023-07-24

        $redis = Cache::store('redis')->handler();
        $redisKey = config('redis_key.recommend_data_key');
        if($playPlatform ==1) { // 微信小程序
            $redisKey = config('redis_key.recommend_data_key');
        }else if($playPlatform == 2){ // 抖音小程序.
            $redisKey = config('redis_key.tiktok_recommend_data_key');
        }

        $length = $redis->scard($redisKey);

        if (empty($length)) {
            $where = [
                ['is_recommended', '=', 1],
                ['is_delete', '=', 0],
                ['is_shelves', '=', 1],
                ['video_type_id', 'NOT IN', config('enum.test')],
                ['play_platform','find in set',$playPlatform] // by add huangxiaoshan 2023-07-24
            ];
            $data = $this->videosModel->getDataByWhere($where, 'cover_img, id, video_type_id, name, synopsis', 'sort desc');
            if (empty($data)) {
                return [];
            }

            foreach ($data as $key => $item) {
                $item['number_of_sets'] = $this->videoDetailsModel->getInfoByWhere(['video_id' => $item['id']], 'sort', 'sort desc')['sort'];
                $data[$key]['number_of_sets'] = $item['number_of_sets'];
                $redis->sadd($redisKey, json_encode($item));
            }

            $redis->expire($redisKey, 43200);
        } else {
            $result = $redis->smembers($redisKey);
            $data = [];
            foreach ($result as $item) {
                $data[] = json_decode($item, true);
            }
        }
        return $data;
    }

    /**
     * 获取付费视频
     * 
     * @dateTime 2022/09/05
     * @author zhixiang0215@126.com
     * @param int videoDetailId
     * @param int uid
     * @return array
     */
    public function showPayForVideo($params, int $uid)
    {
        $videoDetailId = (int)$params['video_detail_id'];
        $play_platform = $params['play_platform'] ?? 1;
        $videoDetailData = $this->videoDetailsModel->getInfoById($videoDetailId, 'is_pay, pay_amount, video_id, sort');
        $redis = Cache::store('redis')->handler();
        $redis->select(8);
        // 获取自定义收费配置
        $userInfo = $this->userModel->getInfoById($uid, 'money, activation_time, official_account_id');
        $userLoginKey = config('redis_key.api.user_login') . $uid;
        $userCacheInfo = $redis->get($userLoginKey);
        $userCacheInfo = $userCacheInfo ? json_decode($userCacheInfo, true) : [];
        $userInfo['link_id'] = !empty($userCacheInfo['link_id']) ? $userCacheInfo['link_id'] : null;
        $customChargeConfigureData = [];

        // 判断是否是挂载的小程序 获取自定义收费设置
        $mountKey = config('redis_key.api.user_login_mount_key').$uid;
        $mountPlatform = $redis->get($mountKey);

        if ($mountPlatform == 1) {
            $customChargeConfigureData = $this->mountedAppletCustomRechargeConfigModel->getInfoByWhere(['platform' => 1, 'video_id' => $videoDetailData['video_id']], 'sort, pay_amount, recharge_template_id, is_new_version');

            if (!empty($customChargeConfigureData['is_new_version'])) {
                $isNewVersion = $customChargeConfigureData['is_new_version'];
                $customChargeConfigureData = $this->customRechargeTemplateModel->getInfoByWhere(['id' => $customChargeConfigureData['recharge_template_id'], 'video_id' => $videoDetailData['video_id']], 'sort, charge_type, pay_amount, interval_recharge');
                if ($customChargeConfigureData) {
                    $customChargeConfigureData['is_new_version'] = $isNewVersion;
                    if (!empty($customChargeConfigureData) && $customChargeConfigureData['charge_type'] == 2) {
                        $customChargeData = json_decode($customChargeConfigureData['interval_recharge'], true);
                    }
                }
            }
        } else if ($mountPlatform == 2) {
            $customChargeConfigureData = $this->mountedAppletCustomRechargeConfigModel->getInfoByWhere(['platform' => 2, 'video_id' => $videoDetailData['video_id']], 'sort, pay_amount, recharge_template_id, is_new_version');
            if (!empty($customChargeConfigureData['is_new_version'])) {
                $isNewVersion = $customChargeConfigureData['is_new_version'];
                $customChargeConfigureData = $this->customRechargeTemplateModel->getInfoByWhere(['id' => $customChargeConfigureData['recharge_template_id'], 'video_id' => $videoDetailData['video_id']], 'sort, charge_type, pay_amount, interval_recharge');
                if ($customChargeConfigureData) {
                    $customChargeConfigureData['is_new_version'] = $isNewVersion;
                    if (!empty($customChargeConfigureData) && $customChargeConfigureData['charge_type'] == 2) {
                        $customChargeData = json_decode($customChargeConfigureData['interval_recharge'], true);
                    }
                }
            }
        } else if (!empty($userInfo['link_id'])) {
            $linkData = $this->linkModel->getInfoByWhere(['id' => $userInfo['link_id']], 'video_pay_setting_id, is_new_recharge_setting, recharge_template_id');

            if ($linkData['is_new_recharge_setting'] == 1) {
                // 获取自定义的短剧收费配置
                $customChargeConfigureData = $this->videoPayConfigModel->getInfoByWhere(['id' => $linkData['video_pay_setting_id'], 'video_id' => $videoDetailData['video_id']], 'sort, status, pay_amount');
            } else if ($linkData['is_new_recharge_setting'] == 2 && !empty($linkData['recharge_template_id'])) {
                $customChargeConfigureData = $this->customRechargeTemplateModel->getInfoByWhere(['id' => $linkData['recharge_template_id'], 'video_id' => $videoDetailData['video_id']], 'sort, charge_type, pay_amount, interval_recharge');
                if (!empty($customChargeConfigureData) && $customChargeConfigureData['charge_type'] == 2) {
                    $customChargeData = json_decode($customChargeConfigureData['interval_recharge'], true);
                }
            }
        }

        if ($customChargeConfigureData) {
            if ($mountPlatform) {
                // 挂载
                if (empty($customChargeConfigureData['charge_type']) && $customChargeConfigureData['sort'] > $videoDetailData['sort']) {
                    // 兼容旧版本
                    return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::ERROR_NO_CHARGE_REQUIRED];
                } else if (!empty($customChargeConfigureData['charge_type']) && $customChargeConfigureData['charge_type'] == 1 && $customChargeConfigureData['sort'] > $videoDetailData['sort']) {
                    // 新版按固定k币
                    return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::ERROR_NO_CHARGE_REQUIRED];
                } else if (!empty($customChargeConfigureData['charge_type']) && $customChargeConfigureData['charge_type'] == 2 && !empty($customChargeData[0]) && $customChargeData[0]['start'] > $videoDetailData['sort']) {
                    // 新版按区间k币
                    return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::ERROR_NO_CHARGE_REQUIRED];
                }
            } else if (!empty($userInfo['link_id'])) {
                if ($customChargeConfigureData['sort'] > $videoDetailData['sort'] && $linkData['is_new_recharge_setting'] == 1) {
                    // 原版短剧收费设置
                    return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::ERROR_NO_CHARGE_REQUIRED];
                } else if ($linkData['is_new_recharge_setting'] == 2 && $customChargeConfigureData['charge_type'] == 1 && $customChargeConfigureData['sort'] > $videoDetailData['sort']) {
                    // 新版短剧收费设置 并且按固定K币收取
                    return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::ERROR_NO_CHARGE_REQUIRED];
                } else if ($linkData['is_new_recharge_setting'] == 2 && $customChargeConfigureData['charge_type'] == 2 && !empty($customChargeData[0]) && $customChargeData[0]['start'] > $videoDetailData['sort']) {
                    // 新版短剧收费设置 并且按区间K币收取
                    return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::ERROR_NO_CHARGE_REQUIRED];
                }
            }
        } else {
            if ($videoDetailData['is_pay'] != 1) {
                return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::ERROR_NO_CHARGE_REQUIRED];
            }
        }

        // 如果查询空值说明没观看过
        $redis->select(4);
        $key = config('redis_key.video_watch_record').$uid.'-'.$videoDetailData['video_id'];
        // 判断redis是否有观看记录数据 video_watch_record_expire
        if ($redisWatchRecordData = $redis->get($key)) {
            $redisWatchRecordData = json_decode($redisWatchRecordData, true);
            if (in_array($videoDetailId, $redisWatchRecordData)) {
                //加密该集
                $encrypt = $play_platform == 1 ? $this->wechatEncryptPlayData($uid, $videoDetailData) : '';
                $returnData = [
                    'encryptStr' => $encrypt,
                    'sort' => $videoDetailData['sort']
                ];
                return ['code' => Error::SUCCESS_CODE, 'message' => Error::SUCCESS_MESSAGE, 'data' => $returnData];
            }
        }
        $watchDetail = $this->watchPayRecordModel->getInfo(['uid' => $uid, 'video_id' => $videoDetailData['video_id']], 'video_detail_id');
        $videoDetailIds = array_column($watchDetail, 'video_detail_id');

        // 如果不存在扣币记录或者支付记录里没有该集的扣币记录
        if (empty($watchDetail) || empty($videoDetailIds) || !in_array($videoDetailId, $videoDetailIds)) {
            $payAmount = $videoDetailData['pay_amount'];
            if ($customChargeConfigureData) {
                if ($mountPlatform) {
                    if (empty($customChargeConfigureData['is_new_version']) || (!empty($customChargeConfigureData['is_new_version']) && $customChargeConfigureData['charge_type'] == 1)) {
                    $payAmount = $customChargeConfigureData['pay_amount'];
                    } else if (!empty($customChargeConfigureData['is_new_version']) && $customChargeConfigureData['charge_type'] == 2) {
                        foreach ($customChargeData as $value) {
                            if ($videoDetailData['sort'] >= $value['start'] && $videoDetailData['sort'] <= $value['end']) {
                                $payAmount = $value['pay_amount'];
                            }
                        }
                    }
                } else if (!empty($userInfo['link_id'])) {
                    if ($customChargeConfigureData && $linkData['is_new_recharge_setting'] == 1) {
                        // 原版短剧收费设置
                        $payAmount = $customChargeConfigureData['pay_amount'];
                    } else if ($linkData['is_new_recharge_setting'] == 2 && !empty($customChargeConfigureData['charge_type']) && $customChargeConfigureData['charge_type'] == 1) {
                        // 新版短剧收费设置 并且按固定K币收取
                        $payAmount = $customChargeConfigureData['pay_amount'];
                    } else if ($linkData['is_new_recharge_setting'] == 2 && !empty($customChargeConfigureData['charge_type']) && $customChargeConfigureData['charge_type'] == 2 && $customChargeData) {
                        // 新版短剧收费设置 并且按区间K币收取
                        foreach ($customChargeData as $value) {
                            if ($videoDetailData['sort'] >= $value['start'] && $videoDetailData['sort'] <= $value['end']) {
                                $payAmount = $value['pay_amount'];
                            }
                        }
                    }
                }
            }

            if ($userInfo['money'] < $payAmount) {
                return ['code' => Error::FAIL_CODE, 'message' => Error::K_C_IS_INSUFFICIENT];
            }

            Db::startTrans();
            try {
                $saveBool = Db::name('user')->save([
                    'id' => $uid,
                    'money' => $userInfo['money'] - intval($payAmount)
                ]);

                if (!$saveBool) {
                    Db::rollback();
                    return ['code' => Error::FAIL_CODE, 'message' => Error::FAILED_TO_DEDUCT_MONEY];
                }
                // 生成消费记录
                $insertBool = Db::name('watch_pay_record')->insert([
                    'uid'             => $uid,
                    'video_id'        => $videoDetailData['video_id'],
                    'video_detail_id' => $videoDetailId,
                    'money'           => intval($payAmount),
                    'consume_date'    => date('Ymd'),
                    'consume_month'   => date('Ym'),
                    'link_id'         => $userInfo['link_id'],
                    'activation_time' => $userInfo['activation_time'],
                    'created_at'      => time(),
                    'updated_at'      => time()
                ]);

                if (!$insertBool) {
                    Db::rollback();
                    return ['code' => Error::FAIL_CODE, 'message' => Error::FAILED_TO_DEDUCT_MONEY];
                }

                //Db::name('videos')->where(['id' => $videoDetailData['video_id']])->inc('total_consume', intval($payAmount))->update();

                //播放统计相关改redis计数
                $redisCacheSwitch = config('trace.redis_cache_switch');
                if ($redisCacheSwitch) {
                    $redis->select(2);
                    $videoKey = config('redis_key.video_statistic_count_key');
                    $redis->hIncrBy($videoKey, 'total_consume_'.$videoDetailData['video_id'], intval($payAmount));
                    $redis->select(4);
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return ['code' => Error::FAIL_CODE, 'message' => Error::FAILED_TO_DEDUCT_MONEY];
            }
        }
        // 更新redis数据
        if ($redisWatchRecordData = $redis->get($key)) {
            // 修改
            $redisWatchRecordData = json_decode($redisWatchRecordData, true);
            $redisWatchRecordData[] = $videoDetailId;
            $redis->set($key, json_encode($redisWatchRecordData), config('redis_key.video_watch_record_expire'));
        } else {
            // 添加
            $videoDetailIds[] = $videoDetailId;
            $redis->set($key, json_encode($videoDetailIds), config('redis_key.video_watch_record_expire'));
        }

        //加密该集
        $encrypt = $play_platform == 1 ? $this->wechatEncryptPlayData($uid, $videoDetailData) : '';
        $returnData = [
            'encryptStr' => $encrypt,
            'sort' => $videoDetailData['sort']
        ];
        return ['code' => Error::SUCCESS_CODE, 'message' => Error::SUCCESS_MESSAGE, 'data' => $returnData];
    }

    //返回微信新版播放器加密串
    private function wechatEncryptPlayData($uid, $detail, $status = 1): string
    {
        $drama_id = Videos::where('id', $detail['video_id'])->value('drama_id');
        $serialList = [
            "start_serial_no" => $detail['sort'],
            "end_serial_no" => $detail['sort'],
            "status" => $status
        ];
        return WechatService::encryptPlayData($uid, $drama_id, [$serialList]);
    }

    //加密字符串
    public function encryptData($uid, $params, $data)
    {
        $playPlatform = $params['play_platform'] ?? 1;
        $detailId = $params['video_detail_id'];
        $detailData = $this->videoDetailsModel->getCacheInfoById($detailId, 'id,is_pay,pay_amount,video_id,sort');
        if ($playPlatform == 1 && empty($data['is_deduct'])) {
            return $this->wechatEncryptPlayData($uid, $detailData, 2);
        }
        return '';
    }

    //是否需要扣费、弹支付面板
    public function checkVideoPlay($params, $uid)
    {
        $detailId = $params['video_detail_id'];
        $payAmount = !empty($params['pay_amount']) ?  (int)$params['pay_amount'] : 0;
        $order_no = isset($params['order_no']) && !empty($params['order_no']) ? $params['order_no'] : '';

        $detailData = $this->videoDetailsModel->getCacheInfoById($detailId, 'id,is_pay,pay_amount,video_id,sort');
        if (!$detailData) {
            return ['code' => Error::FAIL_CODE, 'message' => '参数错误'];
        }
        $userInfo = $this->userModel->getInfoById($uid, 'money,is_members,expiration_time,first_charge_date');
        if (!$userInfo) {
            return ['code' => Error::FAIL_CODE, 'message' => '请先登录'];
        }

        $videoId = $detailData['video_id'];
        $returnData = [
            'code' => Error::SUCCESS_CODE,
            'message' => Error::SUCCESS_MESSAGE,
            'data' => [
                'money' => $userInfo['money'],
                'first_charge_date' => $userInfo['first_charge_date'] ? (int)$userInfo['first_charge_date'] : 0,
                'is_paid' => 0,
                'is_lock_all' => 0,
                'is_members' => 0,
                'is_recharge' => 0,
                'is_deduct' => 0,
                'order_status' => 0,
            ]
        ];

        $payRecords = $this->payRecordModel
            ->field('id,order_no,type,video_id,total_fee,activation_time,pay_time,refund_status')
            ->where(['uid' => $uid, 'status' => 1])
            ->where('refund_status','<>', PayRecord::REFUND_STATUS_SUCC)
            ->whereIn('type',[1,2,3,4,5,6,7,8,11,12,13,15])
            ->select()->toArray();

        $unlockAll = false;
        foreach ($payRecords as $k => $record) {
            if ($k == 0 && empty($returnData['data']['first_charge_date'])) {
                $returnData['data']['first_charge_date'] = (int)$record['pay_time'];
            }
            if (empty($order_no) && $record['order_no'] == $order_no) {
                $returnData['data']['order_status'] = 1;
            }
            if ($record['type'] == Money::TYPE_UNLOCK_ALL && $record['video_id'] == $videoId && $record['refund_status'] != PayRecord::REFUND_STATUS_SUCC) {
                $unlockAll = true;
            }
        }

        //无需收费
        if (empty($payAmount)) {
            return $returnData;
        }

        //是否已收费
        $videoDetailIds = $this->getVideoPayLog($videoId, $uid);
        if (in_array($detailId, $videoDetailIds)) {
            $returnData['data']['is_paid'] = 1;
            return $returnData;
        }

        if ($unlockAll) {
            $returnData['data']['is_lock_all'] = 1;
            return $returnData;
        }

        //是否会员
        if ($userInfo['is_members'] == 1 && $userInfo['expiration_time'] > time()) {
            $returnData['data']['is_members'] = 1;
            $is_free = $this->memberMatchFree($payRecords, $videoId);
            if ($is_free) {
                return $returnData;
            }
            $returnData['data']['is_deduct'] = 1;
            if ($userInfo['money'] < $payAmount) {
                $returnData['code'] = Error::FAIL_CODE_ONE;
                $returnData['message'] = '购买年卡、半年卡或使用K币可免费观看此剧集';
                $returnData['data']['is_recharge'] = 1;
            }
            return $returnData;
        }

        $returnData['data']['is_deduct'] = 1;
        if ($userInfo['money'] >= $payAmount) {
            return $returnData;
        }

        $returnData['data']['is_recharge'] = 1;
        return $returnData;
    }

    //判断会员用户是否达到剧设置金额免费观看的层次
    public function memberMatchFree($payRecords, $videoId)
    {
        $video = $this->videosModel->getCacheInfoById($videoId, 'type,is_money,launch_start_time');
        if (empty($video) || $video['is_money'] == 0) {
            return true;
        }

        if(empty($payRecords)) {
            return true;
        }

        //将用户的未过期的会员都加起来
        $money = 0;
        $time = time();
        foreach ($payRecords as $key => $value) {
            if ($value['video_id'] == $videoId  && $value['type'] == Money::TYPE_UNLOCK_ALL) {
                return true;
            }
            $start_time = $value['pay_time'];
            switch ($value['type']) {
                case 2:
                    # 年卡
                    $end_time = $start_time + (365 * 24 * 60 * 60);
                    break;
                case 3:
                    # 半年卡
                    $end_time = $start_time + (180 * 24 * 60 * 60);
                    break;
                case 4:
                    # 季卡
                    $end_time = $start_time + (90 * 24 * 60 * 60);
                    break;
                case 5:
                    # 60天卡
                    $end_time = $start_time + (60 * 24 * 60 * 60);
                    break;
                case 6:
                    # 30卡
                    $end_time = $start_time + (30 * 24 * 60 * 60);
                    break;
                case 7:
                    # 10卡
                    $end_time = $start_time + (10 * 24 * 60 * 60);
                    break;
                case 8:
                    # 7卡
                    $end_time = $start_time + (7 * 24 * 60 * 60);
                    break;
                case 11:
                    # 3卡
                    $end_time = $start_time + (3 * 24 * 60 * 60);
                    break;
                case 15:
                    # 1卡
                    $end_time = $start_time + (1 * 24 * 60 * 60);
                    break;
                default:
                    # 不计算...
                    $end_time = 0;
                    break;
            }
            if($end_time != 0 && $end_time > $time) {
                $money += $value['total_fee'];
            }
        }

        if($money < $video['is_money']) {
            //只对投放时间十天内的才进行当前判断
            $launch_end_time = $video['launch_start_time'] + (10 * 24 * 60 * 60);
            if($launch_end_time > $time ) {
                return false;
            }
        }
        return true;
    }

    //检查是否需要观看广告
    public function checkAdVideoPlay($params, $uid)
    {
        $detailId = $params['video_detail_id'];
        $playPlatform = $params['play_platform'] ?? 1;
        $detailData = $this->videoDetailsModel->getCacheInfoById($detailId, 'id,is_pay,pay_amount,video_id,sort');
        if (!$detailData) {
            return ['code' => Error::FAIL_CODE, 'message' => '参数错误'];
        }
        $videoId = $detailData['video_id'];
        $video = $this->videosModel->getCacheInfoById($videoId, 'type,is_money,launch_start_time');
        //是否免费专区视频
        if ($video['type'] != 3) {
            return ['code' => Error::FAIL_CODE, 'message' => '错误的请求'];
        }

        $result = $this->isPlayVideoAd($detailData, $uid);
        /*$encryptStr = '';
        if ($playPlatform == 1) {
            $status = $result ? 2 : 1;  //1是免费  2是付费
            $encryptStr = $this->wechatEncryptPlayData($uid, $detailData, $status);
        }*/

        return [
            'code' => Error::SUCCESS_CODE,
            'message' => Error::SUCCESS_MESSAGE,
            'data' => [
                'is_play_ad' => $result ? 1 : 0,
                //'encryptStr' => $encryptStr
            ]
        ];
    }

    //添加视频广告播放记录
    public function addVideoAdPlayRecord($params, $uid)
    {
        $videoDetailId = $params['video_detail_id'];
        $playPlatform = $params['play_platform'] ?? 1;
        $videoDetailData = $this->videoDetailsModel->getInfoById($videoDetailId, 'id, is_pay, pay_amount, video_id, sort');
        if (!$videoDetailData) {
            return ['code' => Error::FAIL_CODE, 'message' => '参数错误'];
        }

        $userInfo = $this->userModel->getInfoById($uid, 'money, link_id, activation_time, official_account_id, applet_id,is_members,expiration_time');
        $video = $this->videosModel->getInfoById($videoDetailData['video_id'],'id,type');

        //是否免费专区
        if ($video['type'] != 3) {
            return ['code' => Error::FAIL_CODE, 'message' => '错误的请求'];
        }

        $is_play_ad = $this->isPlayVideoAd($videoDetailData, $uid, $userInfo);
        if (!$is_play_ad) {
            return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => '该视频无需观看广告'];
        }
        $isInsert = Db::name('watch_ad_record')->insert([
            'uid' => $uid,
            'video_id' => $videoDetailData['video_id'],
            'detail_id' => $videoDetailId,
            'app_id' => $userInfo['applet_id'] ?? 0,
            'created_at' => time(),
            'updated_at' => time()
        ]);
        if (!$isInsert) {
            return ['code' => Error::FAIL_CODE, 'message' => '添加记录失败'];
        }
        /*$encryptStr = '';
        if ($playPlatform == 1) {
            $encryptStr = $this->wechatEncryptPlayData($uid, $videoDetailData);
        }*/
        return [
            'code' => Error::SUCCESS_CODE,
            'message' => Error::SUCCESS_MESSAGE,
            //'data' => ['encryptStr' => $encryptStr, 'sort' => $videoDetailData['sort']]
            'data' => []
        ];
    }

    //判断是否需要播放广告解锁
    private function isPlayVideoAd($detail, $uid, $userInfo = [])
    {
        if ($detail['is_pay'] <= 0) return false;

        //检查是否会员
        if (!$userInfo) {
            $userInfo = $this->userModel->getInfoById($uid, 'id,is_members,expiration_time');
        }

        if ($userInfo && $userInfo['is_members'] == 1 && $userInfo['expiration_time'] > time()) {
            return false;
        }

        // 检查pay_record表该用户是否有对应此视频解锁全集类型的支付
        $unlockAll = $this->payRecordModel->getInfo([
            'uid' => $uid,
            'type' => Money::TYPE_UNLOCK_ALL,
            'video_id' => $detail['video_id'],
            'status' => 1,
            ['refund_status', '<>', PayRecord::REFUND_STATUS_SUCC]
        ]);

        if (count($unlockAll) > 0) return false;

        $start_time = strtotime(date('Y-m-d'));
        $end_time = strtotime(date('Y-m-d 23:59:59'));
        $records = WatchAdRecord::getOneByWhere([
            'uid' => $uid,
            'video_id' => $detail['video_id'],
            'detail_id' => $detail['id'],
            ['created_at','between', [$start_time, $end_time]]
        ]);

        return $records ? false : true;
    }

    /**
     * 获取用户视频消费记录
     *
     * @param $videoId
     * @param $uid
     * @return array
     */
    private function getVideoPayLog($videoId, $uid)
    {
        $redisObj = Cache::store('redis')->handler();
        $redisObj->select(4);
        $key = config('redis_key.video_watch_record').$uid.'-'.$videoId;

        // 优先从redis获取
        if ($redisWatchRecordData = $redisObj->get($key)) {
            $videoDetailIds = json_decode($redisWatchRecordData, true);
        } else {
            // 否则从数据库获取
            $payData = $this->watchPayRecordModel->getInfo(['video_id' => $videoId, 'uid' => $uid], 'id, video_detail_id');
            $videoDetailIds = array_column($payData, 'video_detail_id');
            $redisObj->set($key, json_encode($videoDetailIds), config('redis_key.video_watch_record_expire'));
        }

        return $videoDetailIds;
    }

    /**
     * 获取搜索视频数据
     * 
     * @dateTime 2022/09/05
     * @author zhixiang0215@126.com
     * @param string name
     * @param int uid
     * @return array
     */
    public function getSearchVideoData(string $name, int $uid, $play_platform=1,$appId=1)
    {
        $name = addslashes(strip_tags($name));

        //增加判断当前链接是否属于分销商
        $is_automatic= $this->getIsAutomatic($uid);
        // by huangxiaoshan 2023-07-24 新增支持按平台进行过滤
        $where = [];
        $where[] = ['play_platform','find in set',$play_platform];
        $where[] = ['is_delete','=',0];
        $where[] = ['is_shelves','=',1];
        //start-----------by zengyang  2023-09-06  区分原始剧和复制剧
        //自投appid,展示自投剧
        // $appId=$params['app_id'];
        // var_dump($appId);exit;
        // $appId为空时, 默认为自投小程序
      //增加一个判断当前链接是否是分销商
        if($is_automatic != 2){
            $where[] = ['is_copy','=',(int)$is_automatic];
        }else{
        if(!is_string($appId) || in_array($appId, config('enum.my_appid'))){
            $where[] = ['is_copy','=',0];
        }else{
            $where[] = ['is_copy','=',1];
        }
	}
        //end
        //新加一个判断是否为广告链接进入，如果是就不限制，不是就限制
        $redis = Cache::store('redis')->handler();
        //新加一个判断是否为广告链接进入，如果是就不限制，不是就限制
        //新加 start
        $redis->select(7);
         //新加 start
        $linkidstatus=$redis->get('link_id_status'.$uid.'-'.$appId);
        if(empty($linkidstatus)||$linkidstatus==0){
            $app=$this->appletModel->getInfoById($appId,'vt_id');
            if(!empty($app['vt_id'])) {
                $vtempte = $this->videoTemplateModel->getInfoById($app['vt_id'], '*');
                if(!empty($vtempte['video_arr'])) {
                    $where[] = ['id','', $vtempte['video_arr']];
                }
            }
        }
        //新加 end 
        //$data = $this->videosModel->getDataByLikeName($name, 'id, name, cover_img, give_count, status');
        $data = $this->videosModel->getDataByLikeNameNew($name, 'id, name, cover_img, give_count, status,original_id,drama_id',$where);
        //start-----------by zengyang  2023-09-06  区分原始剧和复制剧
        //不是自投appid,展示复制剧
        if(!in_array($appId, config('enum.my_appid'))||$is_automatic == 1){
            foreach($data as $k_d =>$v_d){
                $original = $this->videosModel->getInfoById($data[$k_d]['original_id']); 
                if(!empty($original)){
                    $data[$k_d]['name']=$original['name'];//用原始剧的名称替换复制剧的名称
                }
            }
        }
        //end
        
        // end
        $videoIds = array_column($data, 'id');

        // 是否追剧
        $bingeWatchData = $this->bingeWatchModel->getDataByWhere(['video_id' => $videoIds, 'uid' => $uid], 'video_id, sort');
        $isBingeWatchData = array_column($bingeWatchData, 'sort', 'video_id');
        // 总共多少集数
        $videoDetailsData = $this->videoDetailsModel->getInfoByVideoIds($videoIds, 'id, video_id');
        $isCountData = [];
        foreach ($videoDetailsData as $item) {
            $isCountData[$item['video_id']][] = $item['id'];
        }

        // 是否有观看记录
        // $recordData = $this->recordsModel->getDataByWhere(['video_id' => $videoIds, 'uid' => $uid], 'video_detail_id, video_id');
        // $isRecordData = array_column($recordData, 'video_detail_id', 'video_id');

        $redis = Cache::store('redis')->handler();
        $redis->select(7);
        $watchKey = config('redis_key.user_watch_record').$uid;
        $watchData = $redis->get($watchKey);
        if ($watchData) {
            $isRecordData = json_decode($watchData, true);
        } else {
            $watchData = $this->recordsModel->getDataByWhere(['uid' => $uid], 'video_detail_id, video_id');
            $isRecordData = array_column($watchData, 'video_detail_id', 'video_id');
            $redis->set($watchKey, json_encode($isRecordData), config('redis_key.user_watch_record_expire'));
        }

        foreach ($data as $index => $item) {
            $data[$index]['is_chase'] = empty($isBingeWatchData[$item['id']]) ? 0 : 1;
            $data[$index]['sort'] = empty($isBingeWatchData[$item['id']]) ? 0 : $isBingeWatchData[$item['id']];

            $data[$index]['count'] = empty($isCountData[$item['id']]) ? 0 : count($isCountData[$item['id']]);

            $data[$index]['is_look'] = empty($isRecordData[$item['id']]) ? 0 : 1;
            $data[$index]['video_detail_id'] = empty($isRecordData[$item['id']]) ? 0 : $isRecordData[$item['id']];
        }

        return $data;
    }

    /**
     * 获取搜索视频数据
     * 
     * @dateTime 2022/09/05
     * @author zhixiang0215@126.com
     * @param int uid
     * @return array
     */
    public function getHotSearchData(int $uid,$params=[])
    {
        $searchData = $this->searchModel->getSearchData('video_id');
        $videoIds = array_column($searchData, 'video_id');

        // by update huangxiaoshan 2023-07-24 新增根据平台类型进行数据过滤。
        $playPlatform = $params['play_platform'] ?? 1;
        $where = [];
        $where[] = ['play_platform','find in set',$playPlatform];
        $where[] = ['id','in',$videoIds];
        $where[] = ['is_delete','=',0];
        $where[] = ['is_shelves','=',1];

        //$data = $this->videosModel->getDataByWhere(['id' => $videoIds, 'is_delete' => 0, 'is_shelves' => 1], 'id, name');
        $data = $this->videosModel->getDataByWhere($where, 'id, name, sylloge, drama_id');
        //end


        $redis = Cache::store('redis')->handler();
        $redis->select(7);

        // $recordData = $this->recordsModel->getDataByWhere(['video_id' => $videoIds, 'uid' => $uid], 'video_detail_id, video_id');
        // $detailData = array_column($recordData, 'video_detail_id', 'video_id');
        $watchKey = config('redis_key.user_watch_record').$uid;
        $watchData = $redis->get($watchKey);
        if ($watchData) {
            $detailData = json_decode($watchData, true);
        } else {
            $watchData = $this->recordsModel->getDataByWhere(['uid' => $uid], 'video_detail_id, video_id');
            $detailData = array_column($watchData, 'video_detail_id', 'video_id');
            $redis->set($watchKey, json_encode($detailData), config('redis_key.user_watch_record_expire'));
        }

        foreach ($data as $key => $item) {
            $data[$key]['video_detail_id'] = empty($detailData[$item['id']]) ? false : $detailData[$item['id']];
        }

        // 获取显示在搜索页面视频
        // by update huangxiaoshan 2023-07-24 新增根据播放平台类型进行数据过滤。
        $where = [];
        $where[] = ['play_platform','find in set',$playPlatform];
        $where[] = ['is_search','=',1];
        $where[] = ['is_delete','=',0];
        $where[] = ['is_shelves','=',1];
        //$videoData = $this->videosModel->getDataByWhere(['is_delete' => 0, 'is_search' => 1, 'is_shelves' => 1], 'id, name, cover_img, status');
        $videoData = $this->videosModel->getDataByWhere($where, 'id, name, cover_img, status, sylloge, drama_id');
        // end.

        if ($videoData) {

            $videoIds = array_column($videoData, 'id');

            // $recordData = $this->recordsModel->getDataByWhere(['video_id' => $videoIds, 'uid' => $uid], 'video_detail_id, video_id');
            // $result = array_column($recordData, 'video_detail_id', 'video_id');

            $videoDetailsData = $this->videoDetailsModel->getInfoByVideoIds($videoIds, 'id, video_id');
            $isCountData = [];
            foreach ($videoDetailsData as $item) {
                $isCountData[$item['video_id']][] = $item['id'];
            }

            foreach ($videoData as $key => $item) {
                $videoData[$key]['video_detail_id'] = empty($detailData[$item['id']]) ? 0 : $detailData[$item['id']];
                $videoData[$key]['count'] = empty($isCountData[$item['id']]) ? 0 : count($isCountData[$item['id']]);
            }
        }

        return ['data' => $data, 'recommended' => $videoData];
    }

    // 获取短剧信息及视频
    public function getVideoInfo($videoId)
    {
        $videoData = $this->videosModel->getInfoById($videoId, 'cover_img, name, update_sort');
        $detailData = $this->videoDetailsModel->getAllDataByVideoId($videoId, 'id, sort', 'sort asc', 5);

        $videoData['id'] = $videoId;
        $videoData['detail_data'] = $detailData;

        return $videoData;
    }

    // 获取指定短剧剧集列表
    public function getVideoList($videoId)
    {
        $fields = 'id, video_id, url, sort';
        // 获取所有视频
        $allVideoData = $this->videoDetailsModel->getDataByWhere(['video_id' => $videoId, 'is_pay' => 0], $fields);

        return $allVideoData;
    }

    // 分享
    public function share($videoDetailId, $uid)
    {
        // 分享数加1
        $bool = $this->videoDetailsModel->where(['id' => $videoDetailId])->inc('share_count', 1)->update();
        // 该用户的分享次数加1
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $redisKey = config('redis_key.number_of_users_sharing').date('Ymd').'-'.$uid;
        $userShareNum = $redis->get($redisKey);
        if (empty($userShareNum)) {
            $redis->set($redisKey, 1, 86400);
        } else {
            $redis->incr($redisKey);
        }

        if (empty($userShareNum) || $userShareNum < 3) {
            $linkData = $videoPayConfigData = [];
            // 获取用户数据
            $userInfo = $this->userModel->getInfoById($uid, 'official_account_id, money, link_id, applet_id, mobile_system');
            // 获取分享开关数据
            if (!empty($userInfo['applet_id'])) {
                $appletData = $this->appletModel->getInfoById($userInfo['applet_id'], 'share_switch');
                if (!$appletData['share_switch']) {
                    return true;
                }
            } else {
                return true;
            }
            // 获取链接的负责人数据
            if (!empty($userInfo['link_id'])) {
                $linkData = $this->linkModel->getInfoByWhere(['id' => $userInfo['link_id']], 'responsibility_person_id');
            }

            // 获取这部剧设置的每集收费K币
            $detailData = $this->videoDetailsModel->getInfoById($videoDetailId, 'video_id');

            if (!empty($linkData)) {
                $videoPayConfigData = $this->videoPayConfigModel->getInfoByWhere(['official_account_id' => $userInfo['official_account_id'], 'video_id' => $detailData['video_id'], 'responsibility_person_id' => $linkData['responsibility_person_id']], 'pay_amount');
            }

            if (!empty($videoPayConfigData)) {
                $money = $userInfo['money'] + $videoPayConfigData['pay_amount'];
            } else {
                $videoPayConfigData = $this->videoDetailsModel->getInfoByWhere(['video_id' => $detailData['video_id'], 'is_pay' => 1], 'pay_amount');
                $money = $userInfo['money'] + $videoPayConfigData['pay_amount'];
            }

            // 分享三次以内（包含三次）每次赠送当前剧的每集收费K币
            $saveData = [
                'id' => $uid,
                'money' => $money,
                'updated_at' => time()
            ];
            $this->userModel->edit($saveData);

            // 添加充值记录
            $this->payRecordModel->edit([
                'uid' => $uid,
                'video_id' => $detailData['video_id'],
                'name' => '分享',
                'type' => 10,
                'number' => $videoPayConfigData['pay_amount'],
                'status' => 1,
                'pay_time' => time(),
                'consume_date' => date('Ymd'),
                'consume_month' => date('Ym'),
                'created_at' => time(),
                'official_account_id' => $userInfo['official_account_id'],
                'total_fee' => '0.00',
                'device_type' => WechatService::getDeviceType($userInfo['mobile_system'] ?? ''),
            ]);
        }

        return $bool ? true : false;
    }

    // 播放完毕后跳转的短剧
    public function getOtherVideoList($uid,$params=[])
    {
        $redis = Cache::store('redis')->handler();
        // $key = config('redis_key.get_other_video_data').$uid;
        $redis->select(7);
        // $result = $redis->get($key);

        // if ($result) {
        //     return json_decode($result, true);
        // }

        // 方案 true为随机切换 false弹窗
        $result['other_video_programme'] = config('enum.get_other_video_programme');

        // $recordData = $this->recordsModel->getDataByWhere(['uid' => $uid], 'video_id');
        // $videoIds = array_column($recordData, 'video_id');
        $watchRecordKey = config('redis_key.get_user_watch_data').$uid;
        $watchData = $redis->get($watchRecordKey);
        if ($watchData) {
            $videoIds = json_decode($watchData, true);
        } else {
            $recordData = $this->recordsModel->getDataByWhere(['uid' => $uid], 'video_id');
            $videoIds = array_column($recordData, 'video_id');
            $redis->set($watchRecordKey, json_encode($videoIds), 1800);
        }

        $play_platform = $params['play_platform'] ?? 1; // by add huangxiaoshan 2023-07-24 按平台过滤
        $data = $this->videosModel->getDataByWhere([['id', 'not in', $videoIds], ['is_shelves', '=', 1],['play_platform','find in set',$play_platform]], 'id, name, cover_img', 'total_consume desc', 6);
        $result['data'] = $data;
        // $redis->set($key, json_encode($result), 1800);

        return $result;
    }


    //获取最近观看的一部影片
    public function getRecentlyWatchVideo($uid)
    {
        $info = Records::where(['uid' => $uid])->field('uid,video_id,video_detail_id')->order('updated_at','DESC')->limit(1)->find();
        if ($info){
            return [
                'video_id' => $info->video_id,
                'video_detail_id' => $info->video_detail_id,
                'video_title' => $info->video->name ?? '',
                'video_detail_title' => $info->videoDetail->name ?? '',
                'video_cover_img' => $info->video->cover_img ?? '',
                'video_detail_no' => $info->videoDetail->sort ?? '',
                'drama_id' => $info->video->drama_id ?? '',
            ];
        }
        return [];
    }

    /**
     * 判断是否为分销商推广链接
     *
     * @param [type] $uid  用户id
     * @return int
     */
    public function getIsAutomatic($uid){
        $linkIdKey = config('redis_key.api.user_login');
        $this->redis->select(8);
        $linkId=json_decode($this->redis->get($linkIdKey . $uid),true);
        if (!empty($linkId['link_id'])) {
            $linklist=$this->linkModel->getInfoByWhere(['id'=>$linkId['link_id']],'responsibility_person_id');
            if (!empty($linklist)) {
                $responsibility = $this->responsibilityPersonModel->getInfoByWhere(['id' => $linklist['responsibility_person_id']], 'company_id');
                if(!empty($responsibility)) {
                    $data = $this->companyModel->getInfoById($responsibility['company_id'], 'is_distributor');
                    return isset($data['is_distributor']) ? (int)$data['is_distributor'] : 2;
                }
            }
        }
        return 2;
    }
}